#!python
# -*- coding: gbk -*-
from cgi import parse, parse_qs
import json

def application(env, start_response):
    #for k,v in env.items():
    #    yield "%s=%s\n" % (str(k),str(v))
    q=env["QUERY_STRING"]
    fname="e:/d/tiankong_2.csv"
    q1=parse_qs(q)
    try:
        start = int(q1["start"][0])
        count = int(q1["count"][0])
    except:
        start_response("400 Bad Request",[("Content-Type","text/html")])
        #raise StopIteration
        return [""]
    if q1.has_key("filename"):
        fname = q1["filename"][0]
    start_response("200 OK",[("Content-Type","application/json")])
    #yield """<meta charset="gbk" />"""
    #yield """<title>fuck you</title>"""
    data=[]
    with open(fname, "r") as fp:
        i=0
        for line in fp:
            line = line.strip("\r\n").decode("gbk").encode("utf-8")
            i+=1
            if i ==1:
                continue
            if i < start:
                continue
            if i >= (start + count):
                break
            items=line.split(",")
            data.append(items)
            #s = """<p><h1>%s</h1><br /><img src="%s" /><p>%s</p><a href="%s">download</a></p>\n""" % (
          #          items[0],items[1],items[2],items[3])
    return [json.dumps(data)]


